import { createStore } from 'vuex'
// import { getRouter } from '@/api/user'
import { userRouter} from '@/assets/user.js'
import { dynamicRouter } from '@/router/index'
// 递归路由,获取完整的路由对象
export function generateAsyncRouter(routerMap, serverRouterMap) {
  serverRouterMap.forEach(function(item) {
    item.component = routerMap[item.component]
    if (item.children && item.children.length > 0) {
      generateAsyncRouter(routerMap, item.children)
    }
  })
  return serverRouterMap
}
export default createStore({
  state: {
    // 侧边栏控制
    sideCollapse: false,
    // 页面级别loading控制
    loading: false,
    // 左侧菜单栏动态控制
    routes: []
  },
  getters: {
    setCollapse: state => state.sideCollapse,
    setLoading: state => state.loading,
    setRouter: state => state.routes
  },
  mutations: {
    SET_SIDE_COLLAPSE(state, status) {
      state.sideCollapse = status
    },
    SET_LOADING(state, status) {
      state.loading = status
    },
    SET_ROUTE(state, status) {
      state.routes = status
    }
  },
  actions: {
    setSideCollapse({ commit }, status) {
      commit('SET_SIDE_COLLAPSE', status)
    },
    setLoading({ commit }, status) {
      commit('SET_LOADING', status)
    },
    addRouter({ commit }, status) {
      return new Promise(resolve => {
        // getRouter().then(res => {
        //   const { data } = res
        //   const accessedRoutes = generateAsyncRouter(dynamicRouter, data)
        //   commit('SET_ROUTE', accessedRoutes)
        //   console.log(accessedRoutes, '菜单权限')
        //   resolve(accessedRoutes)
        // })
        setTimeout(() => {
          const accessedRoutes = generateAsyncRouter(dynamicRouter, userRouter)
          commit('SET_ROUTE', accessedRoutes)
          console.log(accessedRoutes, '菜单权限')
          resolve(accessedRoutes)
        }, 300);
      })
    }
  }
})
